import '@ant-design/compatible/assets/index.css';
import { Button, Row, Col, Tabs, message } from 'antd';
import React, { useState, useEffect } from 'react';
import router from 'umi/router';
import { useActivate } from 'react-activation';
import { useRequest } from '@umijs/hooks';
import styles from './index.less'
import AuthComponent from '@/components/Authorized/AuthComponent';
import DetailInfo from './components/DetailInfo'
import CommunicationRecord from './components/CommunicationRecord'
import PicInfo from './components/PicInfo'
import PicUpload from '../lostItemForm/components/PicUpload'
import ShowPic from '../lostItemForm/components/ShowPic'
import { lostArticlesDetails, getImgByRelevance, addUpdateLostArticlesInfo } from '../lostItemForm/service'

const LostItemDetail = () => {

  // 遗失物品基础信息
  const stateStr = sessionStorage.getItem('/lostItemManage/lostItemDetail');
  const stateObj = stateStr ? JSON.parse(stateStr) : {};

  // 图片上传弹窗显隐
  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false)
  // 图片管理弹窗显隐
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false)
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({ goodFileList: [], touristFileList: [], paperFileList: [] })
  // 图片数组
  const [lostItemPicArr, handleLostItemPicArr] = useState([])
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([])

  // 遗失物品详情接口
  const { data: lostArticlesDetailsD = {}, run: lostArticlesDetailsR } = useRequest(params => lostArticlesDetails(params), {
    manual: true
  })
  // 遗失物品图片接口
  const { run: getImgByRelevanceR } = useRequest(params => getImgByRelevance(params), {
    manual: true,
    onSuccess: (res) => {
      handleOriginPicArr(res)
      handleLostItemPicArr(res)
      let goodFileListData = res.filter(item => {
        return item.oneType === 1
      })

      let touristFileListData = res.filter(item => {
        return item.oneType === 2
      })

      let paperFileListData = res.filter(item => {
        return item.oneType === 3
      })

      handleLostItemPicture({ goodFileList: goodFileListData, touristFileList: touristFileListData, paperFileList: paperFileListData })
    }
  })
  // 新增、编辑遗失物品接口
  const { run: addUpdateLostArticlesInfoR } = useRequest(params => addUpdateLostArticlesInfo(params), {
    manual: true,
    onSuccess: (res, params) => {
      message.success('修改图片成功')
      getImgByRelevanceR({ relevance: stateObj.lostNumber })
      handleLostItemPicVisible(false)
      handleLostItemPicManageVisible(false)
    },
    onError: (res) => {
      message.error('修改图片失败')
    }
  })

  // 跳转到修改
  const editInfo = () => {
    if (lostArticlesDetailsD.closeState === 2) {
      message.warning('请选择未结案遗失物品')
    } else {
      sessionStorage.setItem(
        '/lostItemManage/lostItemForm',
        JSON.stringify({ type: 'edit', random: Math.random(), lostNumber: stateObj.lostNumber })
      )
      router.push('/banksearchSystem/lostItemManage/lostItemForm?id=' + stateObj.lostNumber)
    }
  }

  // 返回
  const back = () => {
    router.push('/banksearchSystem/lostItemManage/lostItemInfoManage')
  }

  // 新增图片/改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = stateObj.lostNumber
        img.push(imgInfo)
      })
    }

    // 修改后带有id(原本存在后台)的图片
    let lostItemPicIdArr = img.filter(item => {
      return item.id
    })
    // 新增加的图片
    let lostItemPicNotIdArr = img.filter(item => {
      return !item.id
    })
    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    addUpdateLostArticlesInfoR({ lostNumber: stateObj.lostNumber, lostCategory: stateObj.lostCategory, img: [...updateArr, ...lostItemPicNotIdArr] })
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    let obj = {};
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }

    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(img).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    addUpdateLostArticlesInfoR({ lostNumber: stateObj.lostNumber, lostCategory: stateObj.lostCategory, img: updateArr })
  }

  useEffect(() => {
    lostArticlesDetailsR({ lostNumber: stateObj.lostNumber })
    getImgByRelevanceR({ relevance: stateObj.lostNumber })
  }, [])

  // 缓存
  useActivate(() => {
    lostArticlesDetailsR({ lostNumber: stateObj.lostNumber })
    getImgByRelevanceR({ relevance: stateObj.lostNumber })
  })

  return (
    <div className={styles.lostItemDetail}>
      <Row>
        <Col span={18}>
          <p>遗失物品详情</p>
          <p>遗失编号：{lostArticlesDetailsD.lostNumber}</p>
          <p>详情类型：遗失</p>
        </Col>
        <Col span={6}>
          <Button type='primary' onClick={() => {
            if (lostItemPic.goodFileList.length === 0 && lostItemPic.touristFileList.length === 0 && lostItemPic.paperFileList.length === 0) {
              handleLostItemPicVisible(true)
            } else {
              handleLostItemPicManageVisible(true)
            }
          }}>图片管理</Button>
          <AuthComponent authCode='lostItemManage.lostItemInfoManage.edit'>
            <Button type='primary' onClick={() => editInfo()}>修改</Button>
          </AuthComponent>
        </Col>
      </Row>
      <Tabs defaultActiveKey="1">
        <Tabs.TabPane tab="详情" key="1">
          <DetailInfo lostArticlesDetailsD={lostArticlesDetailsD}></DetailInfo>
        </Tabs.TabPane>
        <Tabs.TabPane tab="沟通记录" key="2">
          <CommunicationRecord relevance={stateObj.lostNumber}></CommunicationRecord>
        </Tabs.TabPane>
        <Tabs.TabPane tab="图片" key="3">
          <PicInfo lostItemPicArr={lostItemPicArr}></PicInfo>
        </Tabs.TabPane>
      </Tabs>
      <div className={styles.backBtn}>
        <Button type='primary' onClick={() => back()}>返回</Button>
      </div>

      {
        lostItemPicVisible && <PicUpload
          onSubmit={async value => {
            const success = await handleImgs(value)
          }}
          onCancel={() => handleLostItemPicVisible(false)}
          lostItemPicVisible={lostItemPicVisible}
          lostItemPic={lostItemPic}
        ></PicUpload>
      }
      {
        lostItemPicManageVisible && <ShowPic
          onSubmit={async value => {
            const success = await handleDelImgs(value)
          }}
          toUpload={(value) => {
            handleLostItemPicture(value)
            handleLostItemPicManageVisible(false)
            handleLostItemPicVisible(true)
          }}
          onCancel={() => handleLostItemPicManageVisible(false)}
          lostItemPicManageVisible={lostItemPicManageVisible}
          lostItemPic={lostItemPic}
        ></ShowPic>
      }
    </div>
  );
};

export default LostItemDetail;
